Decimal String Utilities

Fixed digit count

This utility converts a floating-point number to a string with fixed digits. This is a common task when dealing with currency or fixed precision.

// Strip a floating point's digits to #.### -- you set the digits
function stripDigits(aNumber, digits)
{
    var str = "" + aNumber
    var b = str.lastIndexOf(".")
  
    // add decimal point if needed
    if (b < 0) str += "." 
  
    // pad with extra zeros in case we have too "round" a number
    for (var i = 0; i < digits; i++) str += "0"

    // extract existing decimal or just return
    if (b >= 0) return(str).substring(0,b+1+digits)
    return str
}

Strip dollar signs

This utility strips dollar signs from a string and returns a floating-point value. Use this function as a filter to evaluate currency form data so users may use dollar signs without crashing your applets.

// Allow for dollar signs in numeric input
function stripDollar(aString)
{
    // An empty field means skip and return zero
    if (aString=="") return 0

    // Check if a dollar sign is found
    var dollar = aString.indexOf("$")
    var myStr = ""+aString

    // If so, skip past it
    if (dollar >= 0)
    {
        var len = aString.length
        myStr = ""+aString.substring(dollar+1, len)
    }

    // Evaluate the rest of the string as a floating point
    return parseFloat(myStr)
}
Copyright ©2000 by Charles River Media, All Rights Reserved